<template>
  <div v-if="isOpen" class="fixed inset-0 z-50 flex items-center justify-center">
    <div class="absolute inset-0 bg-black opacity-50" @click="close"></div>
    <div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl z-10 p-6 w-full max-w-lg">
      <div class="flex justify-between items-center mb-4">
        <h3 class="text-lg font-semibold dark:text-white">加入申请管理</h3>
        <button @click="close" class="text-gray-400 hover:text-gray-500 dark:text-gray-500 dark:hover:text-gray-400">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>
      </div>
    
      <div v-if="loading" class="text-center py-6">
        <div class="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-indigo-500 mx-auto"></div>
        <p class="mt-2 text-sm text-gray-500 dark:text-gray-400">加载申请中...</p>
      </div>
    
      <div v-else-if="requests.length === 0" class="text-center py-6 text-gray-500 dark:text-gray-400">
        暂无加入申请
      </div>
    
      <div v-else class="space-y-3 max-h-96 overflow-y-auto">
        <div 
          v-for="request in requests" 
          :key="request.id"
          class="bg-gray-50 dark:bg-gray-700 rounded-lg p-4"
        >
          <div class="flex items-start justify-between mb-3">
            <div class="flex items-center space-x-3">
              <div class="text-2xl">{{ request.avatar || '👤' }}</div>
              <div>
                <h4 class="font-medium dark:text-white">{{ request.username }}</h4>
                <p class="text-sm text-gray-500 dark:text-gray-400">
                  申请加入群组
                </p>
              </div>
            </div>
            <span class="text-xs bg-blue-100 text-blue-800 py-1 px-2 rounded-full dark:bg-blue-900 dark:text-blue-200">
              {{ formatDate(request.created_at) }}
            </span>
          </div>
        
          <div class="flex space-x-2">
            <button 
              @click="handleRequest(request.id, 'accepted')"
              :disabled="request.processingAccept"
              class="flex-1 px-3 py-1.5 text-sm font-medium text-white bg-green-600 hover:bg-green-700 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 disabled:opacity-50"
            >
              {{ request.processingAccept ? '处理中...' : '同意' }}
            </button>
            <button 
              @click="handleRequest(request.id, 'rejected')"
              :disabled="request.processingReject"
              class="flex-1 px-3 py-1.5 text-sm font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600 disabled:opacity-50"
            >
              {{ request.processingReject ? '处理中...' : '拒绝' }}
            </button>
          </div>
        </div>
      </div>
      
      <div class="flex justify-end mt-6">
        <button 
          @click="close"
          class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md shadow-sm hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:bg-gray-700 dark:text-gray-300 dark:border-gray-600 dark:hover:bg-gray-600"
        >
          关闭
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, watch } from 'vue';
import { useToast } from 'vue-toastification';
import axios from 'axios';

export default {
  name: 'GroupJoinRequests',
  props: {
    isOpen: {
      type: Boolean,
      required: true
    },
    groupId: {
      type: String,
      required: true
    }
  },
  emits: ['close', 'request-responded'],
  setup(props, { emit }) {
    const toast = useToast();
    const requests = ref([]);
    const loading = ref(true);
    
    const loadRequests = async () => {
      if (!props.groupId) return;
      
      try {
        loading.value = true;
        const response = await axios.get(`/api/groups/${props.groupId}/join-requests`);
        requests.value = response.data.map(req => ({
          ...req,
          processingAccept: false,
          processingReject: false
        }));
      } catch (err) {
        console.error('加载加入申请失败:', err);
        if (err.response?.status !== 403) {
          toast.error('无法加载加入申请');
        }
      } finally {
        loading.value = false;
      }
    };
    
    const handleRequest = async (requestId, action) => {
      const request = requests.value.find(req => req.id === requestId);
      if (!request) return;
      
      if (action === 'accepted') {
        request.processingAccept = true;
      } else {
        request.processingReject = true;
      }
      
      try {
        await axios.put(`/api/groups/${props.groupId}/join-requests/${requestId}`, { action });
        
        // 从列表中移除这个申请
        requests.value = requests.value.filter(req => req.id !== requestId);
        
        toast.success(action === 'accepted' ? '已同意加入申请' : '已拒绝加入申请');
        emit('request-responded', { requestId, action });
      } catch (err) {
        console.error('处理申请失败:', err);
        toast.error(err.response?.data?.message || '处理申请失败');
        
        if (action === 'accepted') {
          request.processingAccept = false;
        } else {
          request.processingReject = false;
        }
      }
    };
    
    const formatDate = (dateString) => {
      const date = new Date(dateString);
      const now = new Date();
      const diffInMs = now.getTime() - date.getTime();
      const diffInDays = Math.floor(diffInMs / (1000 * 60 * 60 * 24));
      
      if (diffInDays === 0) {
        return '今天';
      } else if (diffInDays === 1) {
        return '昨天';
      } else if (diffInDays < 7) {
        return `${diffInDays}天前`;
      } else {
        return date.toLocaleDateString('zh-CN');
      }
    };
    
    const close = () => {
      emit('close');
    };
    
    // 监听模态框打开状态
    watch(() => props.isOpen, (newVal) => {
      if (newVal) {
        loadRequests();
      }
    });
    
    onMounted(() => {
      if (props.isOpen) {
        loadRequests();
      }
    });
    
    return {
      requests,
      loading,
      handleRequest,
      formatDate,
      close
    };
  }
};
</script> 